#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMenu, QAction, QToolBar

from .menu import MENU_CONFIG, TOOLBAR_CONFIG
from logger import logger
from context import context


class MenuManager:
    def __init__(self, main_window):
        self.main_window = main_window
        self.setup_menus()
        self.setup_toolbars()

    def setup_menus(self):
        logger.debug("Setting up menus...")
        # 根据配置批量创建菜单
        menu_bar = self.main_window.menuBar()
        menu_bar.clear()
        for menu_name, menu_items in MENU_CONFIG.items():
            menu = self.create_menu_from_config(menu_name, menu_items)
            menu_bar.addMenu(menu)

    def setup_toolbars(self):   
        logger.debug("Setting up toolbars...")
        for toolbar_name, toolbar_items in TOOLBAR_CONFIG.items():
            toolbar = self.create_toolbar_from_config(toolbar_name, toolbar_items)
            self.main_window.addToolBar(toolbar)

    def create_action(self,item):
        """
        创建动作
        """
        action = QAction(item["名称"], self.main_window)
        
        # 设置状态栏提示(如果有)
        if "状态提示" in item:
            action.setStatusTip(item["状态提示"])
        
        # 设置快捷键(如果有)
        if "快捷键" in item:
            action.setShortcut(item["快捷键"])
            
        # 设置是否可勾选
        if item.get("checkable"):
            action.setCheckable(True)
    
        return action

    def connect(self, action, item):
        """
        连接信号和槽
        """
        if "signal" not in item:
            logger.warning(f"菜单项 {item['名称']} 没有信号配置")
            return
        
        if "slot" not in item:
            logger.warning(f"菜单项 {item['名称']} 没有槽配置")
            return
        
        # 使用信号和槽连接
        signal_name = item["signal"]
        if not hasattr(action, signal_name):
            logger.warning(f"菜单项 {item['名称']} 的信号 {signal_name} 不存在")
            return

        slot = item["slot"]    
        target = slot[0]
        method = slot[1]
        target = context.get(target)

        # 获取指定的信号
        if target is None or not hasattr(target, method):
            logger.warning(f"菜单项 {item['名称']} 的槽 {method} 不存在")
            return
            
        slot = getattr(target, method)
        signal = getattr(action, signal_name)
        if item.get("from_signal"):
            from_signal = item["from_signal"]
            from_target = from_signal[0]
            from_method = from_signal[1]
            from_target = context.get(from_target)
            from_slot = getattr(from_target, from_method)
            from_slot.connect(lambda value: self.__set_action_checked(action, value))

        signal.connect(slot)

    def __set_action_checked(self, action, value):
        logger.debug(f"设置菜单项 {action.text()} 的状态为 {value}")
        action.blockSignals(True)
        action.setChecked(value)
        action.blockSignals(False)

    def create_menu_from_config(self, menu_name, items):
        """
        根据配置创建菜单
        
        Args:
            main_window: 主窗口实例
            menu_name: 菜单名称
            items: 菜单项配置列表
            
        Returns:
            QMenu: 配置好的菜单
        """
        menu = QMenu(menu_name, self.main_window)
        
        for item in items:
            # 分隔线
            if item.get("separator"):
                menu.addSeparator()
                continue
            logger.debug(f"创建菜单项: {item['名称']}")    
            # 常规菜单项
            action = self.create_action(item)
        
            self.connect(action, item)

            menu.addAction(action)
        
        return menu

    def create_toolbar_from_config(self, toolbar_name, items):
        """
        根据配置创建工具栏
        
        Args:
            main_window: 主窗口实例
            toolbar_name: 工具栏名称
            items: 工具栏项配置列表
            
        Returns:
            QToolBar: 配置好的工具栏
        """
        toolbar = QToolBar(toolbar_name, self.main_window)
        
        for item in items:
            # 分隔线
            if item.get("separator"):
                toolbar.addSeparator()
                continue
            logger.debug(f"创建工具栏项: {item['名称']}")    
            # 常规菜单项
            action = self.create_action(item)
            if "图标" in item:
                print(__file__)
                # 先尝试从项目根目录的resources文件夹加载图标
                project_root = os.path.dirname(os.path.dirname(__file__))
                icon_path = os.path.join(project_root, "resources", item["图标"])
                
                if os.path.exists(icon_path):
                    logger.debug(f"加载图标: {icon_path}")
                    action.setIcon(QIcon(icon_path))
                else:
                    logger.warning(f"图标文件不存在: {item['图标']}")
                
        
            self.connect(action, item)

            toolbar.addAction(action)
        
        return toolbar
 

def setup_menus(main_window):
    """
    为主窗口设置所有菜单
    
    Args:
        main_window: 主窗口实例，菜单将附加到该窗口
    """
    MenuManager(main_window)